﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Money.Interface
{
    public partial class NewCategoryForm : Form
    {
        private Category _category = new Category();
        private Categories _categories;

        public Category Category
        {
            get { return _category; }
            set { _category = value; }
        }

        public NewCategoryForm(Categories categories)
        {
            _categories = categories;
            InitializeComponent();

            var parentList = from category in _categories orderby category.Name ascending select category;
                        
            _parentCategory.DataSource = parentList.ToList();

            _parentCategory.DisplayMember = "Name";
            _parentCategory.ValueMember = "Id";

            ValidateForm();
        }

        private void Accept_Click(object sender, EventArgs e)
        {
            _category = new Category() { Name = _CategoryName.Text, ParentId = (int)_parentCategory.SelectedValue };

            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void ValidateForm()
        {
            if (_categories.Exists(c => c.Name.Equals(_CategoryName.Text, StringComparison.CurrentCultureIgnoreCase)))
            {
                _acceptButton.Enabled = false;
                _CategoryName.BackColor = Color.Red;
            }
            else
            {
                _acceptButton.Enabled = true;
                _CategoryName.BackColor = Color.White;
            }
        }

        private void _CategoryName_TextChanged(object sender, EventArgs e)
        {
            ValidateForm();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
}
